package services

import (
	"encoding/json"
	"fmt"
	"hg/models"
	"hg/pkg/database"
	"net/http"
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

func UrlToPostDanmu(c *gin.Context) {

	videoIDStr := c.Param("int")
	videoID, err := strconv.Atoi(videoIDStr)
	if err != nil {
		logrus.Errorln(err)
		return
	}
	data := c.PostForm("danmu")
	danmu := new(models.Barrage)
	if err := json.Unmarshal([]byte(data), danmu); err != nil {
		fmt.Println("Error during unmarshal:", err)
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// user := getUserInfo(c)
	// danmu.UserID = user.Id
	danmu.VideoId = videoID
	database.InsertOneDanmu(danmu)
}

func UrlToGetDanmu(c *gin.Context) {
	videoIDStr := c.Param("int")
	videoID, err := strconv.Atoi(videoIDStr)
	if err != nil {
		logrus.Errorln(err)
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid video ID"})
		return
	}
	danmus, _, err := database.GetAllBarrageByVideoID(videoID)
	if err != nil {
		logrus.Errorln(err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Internal Server Error"})
		return
	}
	var danmuStrings []string
	for _, danmu := range danmus {
		danmuJSON, err := json.Marshal(danmu)
		if err != nil {
			logrus.Errorln(err)
			c.JSON(http.StatusInternalServerError, gin.H{"error": "Internal Server Error"})
			return
		}
		danmuStrings = append(danmuStrings, "'"+string(danmuJSON)+"'")
	}
	responseJSON := "[" + strings.Join(danmuStrings, ",") + "]"
	c.JSON(http.StatusOK, responseJSON)
}

// func DanMu(c *gin.Context) {
// 	resp := models.GetDefaultResp()
// 	videoIDStr := c.Param("int")
// 	videoID, err := strconv.Atoi(videoIDStr)
// 	if err != nil {
// 		logrus.Errorln(err)
// 		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid video ID"})
// 		return
// 	}

// 	danmus, cnt ,err := database.GetAllBarrageByVideoID(videoID)
// 	if err != nil {
// 		logrus.Errorln(err)
// 		c.JSON(http.StatusInternalServerError, gin.H{"error": "Internal Server Error"})
// 		return
// 	}
// 	resp.Data=danmus
// 	resp.Count=cnt
// 	c.JSON(http.StatusOK, resp)
// }

func DanMu(c *gin.Context) {
	resp := models.GetDefaultResp()
	videoIDStr := c.Param("int")
	videoID, err := strconv.Atoi(videoIDStr)
	if err != nil {
		logrus.Errorln(err)
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid video ID"})
		return
	}

	danmus, cnt, err := database.GetAllBarrageByVideoID(videoID)
	if err != nil {
		logrus.Errorln(err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Internal Server Error"})
		return
	}
	var simpleDanmus []models.SimpleBarrage
	for _, d := range danmus {
		simpleDanmus = append(simpleDanmus, models.SimpleBarrage{
			Time: convertTime(d.Time),
			Text: d.Text,
		})
	}
	resp.Data = simpleDanmus
	resp.Count = cnt
	c.JSON(http.StatusOK, resp)
}

func convertTime(t int) string {
	// 将十分之一秒转换成分钟:秒的形式
	minute := t / 600
	second := (t % 600) / 10
	return fmt.Sprintf("%02d:%02d", minute, second)
}
